<?php
/**
 * @desc 注册表单处理
 * @author kevin.wang
 * @date 2015-01-01 12:00:00
 */
class RegisterForm extends BaseForm
{
	public $username;
	public $password;
	public $repasswd;
	private $_nameFlag;

	//表单规则
	public function rules()
	{
		return array(
			array('username, password', 'required', 'message'=>'用户名或密码不能为空'),
			array('username', 'unique', 'className'=>'User', 'message'=>'用户名"{value}"已经被注册，请更换'),
			array('username', 'authenRegisterName', 'message'=>'请输入正确邮箱或手机号'),
			array('password', 'authenticate', 'message'=>'密码请输入 6-12 位任意字符'),
			array('repasswd', 'isEqual', 'message'=>'两次输入的密码不一致')
		);
	}
	//密码验证
	public function authenticate($attribute,$params)
	{
		$password = $this->password;
		$len = strlen($password);
		if($len < 6 || $len > 12){
			$this->addError('password',$params['message']);
		}
	}
	//密码比较
	public function isEqual($attribute,$params)
	{
		$password = $this->password;
		$repasswd = $this->repasswd;
		if($repasswd != $repasswd){
			$this->addError('password',$params['message']);
		}
	}
	//用户名校验
	public function authenRegisterName($attribute,$params){
		$username = $this->username;
		$pregMobile = "/^1[3|4|5|8][0-9]\d{4,8}$/";
		$pregEmail = "/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/";
		if(preg_match($pregMobile, $username)){
			$this->_nameFlag = 'mobile';
		}
		if(preg_match($pregEmail, $username)){
			$this->_nameFlag = 'email';
		}
		if(empty($this->_nameFlag)){
			$this->addError('username',$params['message']);
		}
		
	}
	//用户注册
	public function register()
	{
		$data = array(
			"username" => $this->username, 
			"password" => $this->encryPasswd($this->password),
			$this->_nameFlag => $this->username
		);
		$user = new User();
		$result = $user->userRegister($data);
		if(empty($result)){
			return false;
		}
		return true;
	}
}
